﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jint;
namespace DBToExcel.Code
{
    public class ScriptUtil
    {
        /// <summary>
        /// 执行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static object Execute<T>(string expression, Dictionary<string, object> args)
        {
            Type type = typeof(T);
            if (string.IsNullOrEmpty(expression))
            {
                if (type == typeof(int) || type == typeof(decimal) || type == typeof(double) || type == typeof(float))

                {
                    return 0;
                }

                if (type == typeof(DateTime))
                {
                    return DateTime.MinValue;
                }

                if (type == typeof(string))
                {
                    return "";
                }

                return default(T);
            }

            if (type == typeof(int))
            {
                var result = JintExecute(expression, args);
                return Convert.ToInt32(result);
            }
            if (type == typeof(decimal))

            {
                var result = JintExecute(expression, args);
                return Convert.ToDecimal(result);
            }
            if (type == typeof(double))

            {
                var result = JintExecute(expression, args);
                return Convert.ToDouble(result);
            }
            if (type == typeof(DateTime))

            {
                var result = JintExecute(expression, args);
                return Convert.ToDateTime(result);
            }

            return JintExecute(expression, args);
        }


        public static object JintExecute(string expression, Dictionary<string, object> args)
        {
            var engine = new Engine();
            if (args != null)
            {
                foreach (var x in args)
                {
                    engine.SetValue(x.Key, x.Value);
                }
            }
            return engine.Execute(expression).GetCompletionValue().ToObject();
        }

    }
}
